package com.xiaochen.baidu.service.thread;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaochen.baidu.service.IMoiuLoginService;
import com.xiaochen.baidu.service.IMoiuParseService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import okhttp3.ResponseBody;
import retrofit2.Call;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xc
 * @date 2025/10/12/12:37
 * @desc
 */
@AllArgsConstructor
public class CallBackThreadTask implements Supplier<String> {
    private String code;
    private String state;
    private IMoiuParseService moiuParseService;
    
    @SneakyThrows
    @Override
    public String get() {
        Call<ResponseBody> callback = moiuParseService.callback(code, state);
        String result = callback.execute().headers().get("Location");
        Matcher matcher = Pattern.compile("data=([^&]+)").matcher(result);
        if (matcher.find()) {
            String data = matcher.group(1);
            // Base64 解码
            byte[] decodedBytes = Base64.getDecoder().decode(data);
            // 转换为字符串
            String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);
            // URL 解码
            String urlDecodedString = URLDecoder.decode(decodedString, StandardCharsets.UTF_8.name());
            // JSON 解析
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(urlDecodedString);
            // 提取 kdown_session
            return jsonNode.get("data").get("kdown_session").asText();
        }
        return null;
    }
}
